using LanqiQAwebapi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using RabbitMQ;
using LanqiQAwebapi.Todo;
using LanqiQAwebapi.Interface;
using StackExchange.Redis;
using LanqiQAwebapi.ToolsHader;
namespace LanqiQAwebapi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();
          //  builder. services.AddScoped<IUserServer, UserServer>();




            builder.Services.AddDbContext<LanQiQaDBContext>(options =>
            options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

            builder.Services.AddSingleton(new jwt(builder.Configuration));


            //redis缓存
            var section = builder.Configuration.GetSection("Redis:Default");
            //连接字符串
            string _connectionString = section.GetSection("Connection").Value;
            //实例名称
            string _instanceName = section.GetSection("InstanceName").Value;
            //默认数据库 
            int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0"); 
            //redis服务注入
           builder.Services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));
            builder.Services.AddScoped<ICacheService, CacheService>();
            builder.Services.AddScoped<IUserServer, UserServer>(); 
              builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
              {
                  return ConnectionMultiplexer.Connect(_connectionString);

              });
          
            //注入jwt

            builder.Services.AddAuthentication(options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            
            })
               
            .AddJwtBearer(options =>
              {
                  options.TokenValidationParameters = new TokenValidationParameters()
                  {
                      ValidateIssuer = true, //是否验证Issuer
                      ValidIssuer = builder.Configuration["Jwt:Issuer"], //发行人Issuer
                      ValidateAudience = true, //是否验证Audience
                      ValidAudience = builder.Configuration["Jwt:Audience"], //订阅人Audience
                      ValidateIssuerSigningKey = true, //是否验证SecurityKey
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"])), //SecurityKey
                      ValidateLifetime = true, //是否验证失效时间
                      ClockSkew = TimeSpan.FromSeconds(0), //过期时间容错值，解决服务器端时间不同步问题（秒）
                      RequireExpirationTime = true,
                  };
              });
            builder.Services.AddSingleton<Ijwt, jwt>();

            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });

                // 添加JWT Bearer方案到Swagger UI
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = @"Enter 'Bearer' [space] and then your token in the text input below.
                       \n\nExample: 'Bearer 12345abcdef'",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                // 配置安全要求，使得所有API都需要JWT Bearer认证
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                },
                Scheme = "oauth2",
                Name = "Bearer",
                In = ParameterLocation.Header,

            },
            new List<string>()
        }
    });
            });
            // 添加RabbitMQ配置
            /* builder.Services.Configure<RabbitMQSettings>(builder.Configuration.GetSection("RabbitMQ"));

             // 注册RabbitMQ客户端工厂或直接注册服务
             builder.Services.AddSingleton<IRabbitMQService, RabbitMQService>();
 */

            //配置跨域
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowCors", builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

            });
            app.UseCors("AllowCors");
            app.UseAuthentication();
            app.UseAuthorization();
            app.MapControllers();

            app.Run();
        }
    }
}